/*
 Cogumelo v0.1 - INNOTO
Copyright (C) 2010 Innoto Gestión para el Desarrollo Social S.L. <mapinfo@innoto.es>

This program is free software; you can redistribute it and/or
modify it under the2009 terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
USA.
*/

var FileLiftInput = Class.create({
	
		//
		// CONSTRUCTOR
		//
	
	    init: function(selectID, opts) {
			//Check Options from user
			
			this.options = new Object({
				actionUrl : 'action.php?cmd=filelift',
				frameUrl : 'action.php?cmd=filelift&go=blank',
				profile : false,
				privatefoldersid : false,
				autosubmit : false,
				onDelete : null,
				onInfo : null
			});			
			if(opts)
				$.extend(true , this.options,opts);
			
	    	//Atributes of related elements
	    	this.id = selectID;							//container ID
	    	this.frameid = 'flFrame_' + this.id			//iframe ID
			this.formid = 'flForm_' + this.id;			//upload form ID
			this.fileinputid = 'flFile_' + this.id;		//input file id
			this.textinputid = 'flText_' + this.id;		//input text id
			this.infospanid = 'flInfo_' + this.id;			//span to display info
			this.upbuttonid = 'flUp_' + this.id;		//button
			this.downbuttonid = 'flDown_' + this.id;	//button
			this.changebuttonid = 'flCh_' + this.id;	//button
			this.deletebuttonid = 'flDel_' + this.id;	//button
			
			this.textinputname = $('#' + this.id).attr('name');
			this.categorie = $('#' + this.id).attr('fl_cat');
			this.filename = '';	//previous file name 
			this.entityid = false; // unique id for privatefolders mode
			
	    	//DOM elements
			this.DOM = $('#' + this.id);
			this.fram;
	    	this.iDOM;				//<IFRAME> document
	    	this.form;				//<FORM>
	    	this.fileinput;			//<INPUT type="file">
	    	this.textinput;			//<INPUT type="text">
	    	this.infospan;			//<SPAN>
	    	this.upbutton;			//<BUTTON>
	    	this.downbutton;		//<BUTTON>
	    	this.changebutton;		//<BUTTON>
	    	this.deletebutton;		//<BUTTON>
	    	
	    	//detect previus file stored (if exists)
	    	if((this.DOM.attr('value') != '') && (this.DOM.attr('value')!=='undefined'))
	    		this.filename = this.DOM.attr('value');
	    	
			//HTML to insert into container
	    	var dump = '<iframe id="' + this.frameid + '" src="' + this.options.frameUrl + '" scrolling="no" frameborder="0" margin="0" style="display: none;"></iframe>';
	    	dump += '<input type="hidden" id="' + this.textinputid + '" value = "' + this.filename + '" name="' + this.textinputname + '"/>';
	    	dump += '<p class="fl_UI" style="display: none;"><span id="' + this.infospanid + '" class="fl_info"></span>';
	    	dump += '<button type="button" id="' + this.upbuttonid + '" class="fl_button fl_up"></button>';
	    	dump += '<button type="button" id="' + this.downbuttonid + '" class="fl_button fl_down"></button>';
	    	dump += '<button type="button" id="' + this.changebuttonid + '" class="fl_button fl_change"></button>';
	    	dump += '<button type="button" id="' + this.deletebuttonid + '" class="fl_button fl_delete"></button></p>';
	    	
	    	//insert HTML and store DOM objects
	    	this.DOM.html(dump);
	    	
	    	this.syncDOM(0);
	    	
	    	//insert HTML when IFRAME is loaded and launch events
	    	var that = this;
	    	$('iframe#' + this.frameid).bind('load', function() {
	    		that.syncDOM(1);
		    	that.buildUpForm();
		    	that.syncDOM(2);
		    	that.launchEvents();
	    	 });
	    	$('iframe#' + this.frameid).one('load', function() {
		    	//previous file check
		    	if(that.filename) {
		    		dsp = 'ready-down';
		    		that.textinput.val(this.filename);
		    		that.infospan.addClass('fl_loading');
		    		that.askJSON('info');
		    	}
		    	else
		    		that.manageDisplay('ready-up');
		    });
	    	if ($.browser.mozilla)
	    		this.fram.src = "";

	    	this.setCSS();			
	    },

		//
		// DATA COM METHODS
		//
		
		setResponse: function(status, msg, filename) {
			//store the file name
			this.filename = filename;
			//check if status isn't info and display error
			var view;
			switch(status)
			{
			case 'info':
				this.textinput.val(filename);
				view = 'ready-down';
				break;
			case 'deleted':
				view = 'ready-up';
				break;
			default:
				this.textinput.val('');
				view = 'error';
			}
			this.S('script').html('');
			
			this.manageDisplay(view);
			this.infotext = msg;
			this.infospan.html(msg);
			this.infospan.removeClass('fl_loading');
			this.disButtons(false);
		},
		
		askJSON: function(action) {
			this.disButtons(true);
			var that = this;
			postData = {
					'go' : action,
					'prof' : that.options.profile,
					'cat' : that.categorie,
					'name' : that.fileinputid,
					'file' : that.filename,
					'obj' :that.id
			};
			if(this.options.privatefoldersid)
				postData.id = this.options.privatefoldersid;
				
			$.ajax({
				async: false,
				url: that.options.actionUrl,
				type: 'POST',
				dataType: 'json',
				data: postData,
				success: function(data){
					that.setResponse(data.status, data.msg, data.file);
					if(action == 'delete') {
						that.textinput.val('');
						if(that.options.onDelete)
							that.options.onDelete(data);
					}
					if(action == 'info' && that.options.onInfo)
						that.options.onInfo(data);
				}
			});
		},
		
		askDownload: function() {
			this.disButtons(true);
			var url = 'action.php?cmd=filelift&prof=' + this.options.profile + '&go=down&cat=' + this.categorie + '&file=' + this.filename;
			if(this.options.privatefoldersid)
				url += '&id=' + this.options.privatefoldersid;
			window.location = url;
			this.disButtons(false);
		},
	    
		//
		// EVENT RELATED METHODS 
		//
	    
	  	//launch events
	    launchEvents: function() {
	    	var that = this;
	    	//bind the form
	    	this.form.bind('submit', function(e) {
	    		that.infospan.addClass('fl_loading');
	    		that.disButtons(true);
	    	});
	    	//bind the input file
	    	this.fileinput.bind('change', function(e) {
	    		that.infotext = 'File: ' + that.fileinput.val();
	    		that.infospan.html(that.infotext);
	    		//check auto submit
	    		if(that.options.autosubmit) {
	    			that.form.submit();
	    			var dsp = 'ready-down';
	    		}
	    		else
	    			var dsp = 'waiting-up';
	    		that.manageDisplay(dsp);
		    });
	    	//upload button
	    	this.upbutton.bind('click', function(e) {
		    	that.form.submit();
		    });
	    	//download button
	    	this.downbutton.bind('click', function(e) {
		    	that.askDownload();
		    });
	    	//change button
	    	this.changebutton.bind('click', function(e) {
	    		that.fileinput.val('');
		    	that.manageDisplay('ready-up');
		    });
	    	//delete button
	    	this.deletebutton.bind('click', function(e) {
	    		if(that.textinput.val() != '') {
	    			that.infospan.addClass('fl_loading');
	    			that.askJSON('delete');
	    		}
	    		that.fileinput.val('');
		    });
	    	//tips on hover, all buttons
	    	this.DOM.find('button').bind('mouseenter', function(e) {
	    		that.tip(this);
	    	});
	    	this.DOM.find('button').bind('mouseleave', function(e) {
	    		that.untip();
	    	});
		},
	    
	    //
	    //DOM SYNC & ELEMENT FINDING METHODS
	    //
	    
	    //store iframe DOM object for internal use
	    syncDOM: function(mode) {
		    if(!all) var all = false;
		    switch(mode) {
		    	case 0:
		    		//DOM elements
		    		this.fram = $('#' + this.frameid);
		    		this.textinput = $('input#' + this.textinputid);
		    		this.infospan = $('span#' + this.infospanid);
		    		this.upbutton = $('button#' + this.upbuttonid);
		    		this.downbutton = $('button#' + this.downbuttonid);
			    	this.changebutton = $('button#' + this.changebuttonid);
			    	this.deletebutton = $('button#' + this.deletebuttonid);
		    		break;
		    	case 1:
		    		//iframe document
		    		this.iDOM = $('iframe#' + this.frameid).contents();
		    		break;
		    	case 2:
		    		//elements into iframe
		    		this.form = this.S('form#' + this.formid);
			    	this.fileinput = this.S('input#' + this.fileinputid);
		    }
		},
		
		//selects content into the IFRAME DOM
		S: function(selector) {
			//console.debug(this.iDOM.find(selector));
			return this.iDOM.find(selector);
		},
		
		//
		//	DISPLAY METHODS (HTML & CSS)
		//
		
		//manages visibility of elements
		manageDisplay: function(mode) {
			switch(mode) {
				case 'ready-up':
					$('#' + this.frameid).show();
					this.infospan.hide();
					this.upbutton.hide();
					this.downbutton.hide();
					this.changebutton.hide();
					this.deletebutton.hide();
					break;
				case 'ready-down':
					$('#' + this.frameid).hide();
					this.infospan.show();
					this.upbutton.hide();
					this.downbutton.show();
					this.changebutton.hide();
					this.deletebutton.show();
					break;
				case 'waiting-up':
					$('#' + this.frameid).hide();
					this.infospan.show();
					this.upbutton.show();
					this.downbutton.hide();
					this.changebutton.show();
					this.deletebutton.hide();
					break;
				case 'error':
					$('#' + this.frameid).hide();
					this.infospan.show();
					this.upbutton.hide();
					this.downbutton.hide();
					this.changebutton.show();
					this.deletebutton.hide();
					break;
			}
		},
		
		//set & unset information tips
		tip: function(ele) {
			if($(ele).hasClass('fl_up')) {
				this.infospan.html('Subir el archivo');
				this.infospan.addClass('fl_tip');
			}
			else if ($(ele).hasClass('fl_change')) {
				this.infospan.html('Cambiar el archivo a subir');
				this.infospan.addClass('fl_tip');
			}
			else if ($(ele).hasClass('fl_down')) {
				this.infospan.html('Descargar el archivo');
				this.infospan.addClass('fl_tip');
			}
			else if ($(ele).hasClass('fl_delete')) {
				this.infospan.html('Eliminar el archivo');
				this.infospan.addClass('fl_tip');
			}
		},
		
		untip: function() {
			this.infospan.html(this.infotext);
			this.infospan.removeClass('fl_tip');
		},
		
		disButtons: function(bool) {
		if(bool)
				this.DOM.find('button').attr('disabled', 'disabled');
			else
				this.DOM.find('button').removeAttr('disabled', 'disabled');
		},
		
		//set CSS properties of elements
		//set CSS properties of elements
		setCSS: function() {
			/*var alto = $("#"+this.id).css('height');
			var ancho = $("#"+this.id).css('width');
			$('#' + this.frameid).css({
				 'width':ancho,
				 'height': 'auto',
				 'overflow-x':'hidden',
				 'overflow-y':'hidden'
				});
			console.debug(alto)*/
			$.each( $('.fl_UI'), function(i, e) { $(e).show(); } );
		},
		
		//build content into the iframe
	    buildUpForm: function() {
			var dump = '<style>body,  body * {margin: 0;text-align: center; vertical-align: middle;}</style>';
	    	dump += '<form id="' + this.formid + '" action="action.php?cmd=filelift" method="post" target="_self" enctype="multipart/form-data">';
	    	dump += '<input name="prof" value="' + this.options.profile + '" type="hidden"/>';
	    	dump += '<input name="go" value="up" type="hidden"/>';
	    	if(this.options.privatefoldersid)
	    		dump += '<input name="id" value="' + this.options.privatefoldersid + '" type="hidden"/>';
			dump += '<input name="obj" value="' + this.id + '" type="hidden"/>';
			dump += '<input name="cat" value="' + this.categorie + '" type="hidden"/>';
			dump += '<input name="name" value="' + this.fileinputid + '" type="hidden"/>';
	    	dump += '<p><input type="file" name="' + this.fileinputid + '" id="' + this.fileinputid + '" /></p>';
	    	dump += '</form>';
	    	this.S('body').append(dump);
		}		
	});

